package com.ldg.order.controller;

import com.alipay.api.AlipayApiException;
import com.ld.pojo.PayVo;
import com.ld.pojo.TbPayLog;
import com.ld.utils.AlipayTemplate;
import com.ldg.order.entity.Cart;
import com.ldg.order.entity.TbAddress;
import com.ldg.order.entity.TbOrder;
import com.ldg.order.service.OrderService;
import com.ldg.order.service.PayService;
import org.jasig.cas.client.util.AbstractCasFilter;
import org.jasig.cas.client.validation.Assertion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author: Liudao
 * @Date: 2022-10-18-15:11
 * @Description:
 */
@Controller
public class OrderController {

    @Autowired
    private OrderService orderService;

    //查看订单页面
    @RequestMapping({"/","/index"})
    public String index(Model model, HttpSession session) {
        //得到登录名
        Assertion assertion = (Assertion) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
        if (assertion != null) {
            String name = assertion.getPrincipal().getName();
            model.addAttribute("name", name);
            //根据用户名查询地址列表
            List<TbAddress> addressList = orderService.findAddrByUname(name);
            //放到model中
            model.addAttribute("addressList",addressList);
            //在redis中根据用户名查询购物车
            List<Cart> cartList = orderService.findCartByUname(name);
            //将其放到model中
            model.addAttribute("cartList",cartList);
        }
        return "getOrderInfo";
    }

    //保存订单
    @PostMapping("/order/add")
    public String addOrder(TbOrder tbOrder,Model model,HttpSession session){
        //1.1 得到登录名
        Assertion assertion = (Assertion) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
        if (assertion != null) {
            String name = assertion.getPrincipal().getName();
            //model.addAttribute("name", name);
            //添加订单
            orderService.add(name,tbOrder);
            //根据用户名得到日志
            TbPayLog payLog = orderService.findPayLogByUname(name);
            //将paylog放到model中去
            model.addAttribute("paylog",payLog);
        }
        return "pay";
    }

}
